#include "xexec.h"
#include <iostream>

#ifdef _WIN32
#define popen _popen
#endif
using namespace std;

XExec::XExec()
{
}

XExec::~XExec()
{
    Wait();
}

bool XExec::Start(std::string cmd)
{
    auto fp = popen(cmd.c_str(), "r");
    if (fp == 0)
    {
        return false;
    }

    running_ = true;

    fut_ = async([fp, this]()
                 {
        string temp;
        char c;
        while (c = fgetc(fp) )
        {
            if (c == EOF)
            {
                break;
            }
            if (c == '\n')
            {
                lock_guard<mutex> lock(mutx_);
                out_queue_.push(temp);
                temp = "";
                continue;
            };
            
            temp += c;
        }

        pclose(fp);
        running_ = false;
        return true; });

    return true;
}

bool XExec::GetOutput(std::string &out)
{
    if (!out_queue_.empty())
    {
        lock_guard<mutex> lock(mutx_);
        out = move(out_queue_.front());
        out_queue_.pop();
        return true;
    }

    return false;
}
